import * as React from 'react';
import '../styles.less';
import ParagraphCard from '../../../components/ParagraphCard'
import '@zc/netchart/assets/netchart.css'
import '@plantdata/sdk/bundles/pd-sdk.css'
import { PdSDKZcRelation, PdSDKZcGraph, PdSDKZcTiming, PdSDKZcPath } from '@plantdata/sdk'
import * as ReactDom from 'react-dom'
import * as html2canvas from "html2canvas"
import { insertImage, insertHtmlAfterParagraph, insertTextAfterParagraph } from '../../../utils/WordUtil';
import { openDialog } from '../../../utils/WordDialog';
import { PrimaryButton } from 'office-ui-fabric-react';

export interface StatProps {
  keyword: string
  search?: string
  hideMenu?: boolean
  viewIndex?: string
  isNeedParent?: boolean
  res: any
}

export interface StatStates {

}

export default class Assistant extends React.Component<StatProps, StatStates> {
  html
  dialog
  constructor(props, context) {
    super(props, context);
  }

  componentDidMount() {
    this.judgeRender(this.props)
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps && nextProps.keyword !== this.props.keyword) {
      this.judgeRender(nextProps)
    }
  }

  judgeRender = props => {
    const { res, keyword } = props
    const { content } = res
    let resultData = content
    let loadParams = null
    let chartOption = null
    // 判断展示
    if (keyword === 'relation') {
      let nodes = [];
      for (let item of resultData.entities) {
        nodes.push({ id: item })
      }
      loadParams = { id: resultData.entities[0], nodes: nodes };
      chartOption = this.getOptions(resultData, loadParams)
      new PdSDKZcRelation(chartOption)
    } else if (keyword === 'graph' || keyword === 'timing') {
      loadParams = { id: resultData.entities[0] };
      chartOption = this.getOptions(resultData, loadParams)
      keyword === 'graph' ? new PdSDKZcGraph(chartOption) : new PdSDKZcTiming(chartOption)
    } else if (keyword === 'path') {
      loadParams = { id: resultData.entities[0], start: { id: resultData.entities[0] }, end: { id: resultData.entities[1] } };
      chartOption = this.getOptions(resultData, loadParams)
      new PdSDKZcPath(chartOption)
    }
  }

  getOptions = (resultData, loadParams) => {
    return {
      selector: document.getElementById('chart'),
      netChartSettings: {
        payload: {
          data: resultData,
          loadParams: loadParams
        },
        main: {
          settings: {
            toolbar: {
              enabled: false
            }
          }
        }
      },
      infoboxSettings: {
        enable: false
      },
      prompt: {
        enable: false
      },
      filter: {
        enable: false
      },
      page: {
        enable: false
      },
      stats: {
        enable: false
      },
      find: {
        enable: false
      },
      history: {
        enable: false
      },
      path: {
        enable: false
      },
      connects: {
        enable: false
      },
      relation: {
        enable: false
      },
      schema: resultData.schema
    }
  }

  getInsertImg = async () => {
    try {
      // const canvas = await html2canvas(document.querySelector("#chart"), { useCORS: true })
      const canvas = await document.querySelector("canvas")
      const base64 = canvas.toDataURL("image/png")
      return base64

    } catch (error) {
      console.log('error', error)
    }
    return ''
  }

  insertImg = async () => {
    let newImg = await this.getInsertImg()
    insertImage(newImg)
  }

  messageCallback = (arg) => {
    insertImage(arg.message)
    // insertTextAfterParagraph(arg.message)
    // this.insertImg()
    this.dialog.close();
  }

  dialogCallback = (asyncResult) => {
    if (asyncResult.status == "failed") {
    }
    else {
      console.info('弹窗打开成功')
      this.dialog = asyncResult.value;
      this.dialog.addEventHandler(Office.EventType.DialogMessageReceived, this.messageCallback);
    }
  }

  render() {
    const { isNeedParent = true, search, viewIndex } = this.props
    const menuProps = [
      {
        key: 'view',
        text: '预览',
        iconProps: {
          iconName: 'View',
        },
        onClick: () => {
          openDialog(`/assistantDialog?keyword=${search}&index=${viewIndex}`, this.dialogCallback)
        }
      },
      {
        key: 'download',
        text: '插入到word',
        iconProps: {
          iconName: 'Download',
        },
        onClick: this.insertImg
      }
    ]
    return (
      <div className='relation'>
        {isNeedParent ? (
          <div onClick={() => openDialog(`/assistantDialog?keyword=${search}&index=${viewIndex}`, this.dialogCallback)}><ParagraphCard title={search} menuProps={{ items: menuProps }}>
            <div id="chart" ref='relation' style={{ minHeight: '300px' }}></div>
          </ParagraphCard></div>) : (
            <React.Fragment>
              <div id="chart" ref='relation' style={{ height: `${window.innerHeight - 100}px` }}></div>
              <div className="ms-clearfix" style={{ textAlign: 'center', marginTop: '15px' }}>
                <PrimaryButton className="pull-right" onClick={this.handleDialogInsert}>使用</PrimaryButton>
              </div>
            </React.Fragment>
          )}
      </div>
    );
  }

  handleDialogInsert = async () => {
    let newImg = await this.getInsertImg()
    Office.context.ui.messageParent(newImg);
  }
}


